package com.aier.classes.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.eicp.ghostboy.futil.MD5Util;
import net.eicp.ghostboy.futil.RandomUtil;

import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import com.aier.classes.common.InviteRequestUtil;
import com.aier.classes.entity.ClassParent;
import com.aier.classes.entity.ClassStudent;
import com.aier.classes.entity.ClassTeacher;
import com.aier.classes.entity.InviteParent;
import com.aier.classes.entity.InviteTeacher;
import com.aier.classes.entity.RequestParent;
import com.aier.classes.entity.RequestTeacher;
import com.aier.classes.entity.mapper.ClassParentRowMapper;
import com.aier.classes.entity.mapper.ClassStudentRowMapper;
import com.aier.classes.entity.mapper.InviteParentRowMapper;
import com.aier.classes.entity.mapper.InviteTeacherRowMapper;
import com.aier.classes.entity.mapper.RequestParentRowMapper;
import com.aier.classes.entity.mapper.RequestTeacherRowMapper;
import com.aier.classes.service.IClassUserService;
import com.aier.classes.service.IInviteRequestService;
import com.aier.common.common.Constant;
import com.aier.common.dao.ICommonDAO;
import com.aier.common.service.ISysPhoneMessageService;
import com.aier.school.entity.SchoolTeacher;
import com.aier.school.entity.mapper.SchoolTeacherRowMapper;
import com.aier.user.entity.User;
import com.aier.user.service.IUserService;

@Component("inviteRequestService")
public class InviteRequestServiceImpl_J implements IInviteRequestService {
	@Resource(name = "commonDao")
	private ICommonDAO commonDao;

	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "classUserService")
	private IClassUserService classUserService;

	@Resource(name = "sysPhoneMessageService")
	private ISysPhoneMessageService sysPhoneMessageService;

	public void setCommonDao(ICommonDAO commonDao) {
		this.commonDao = commonDao;
	}

	public void setClassUserService(IClassUserService classUserService) {
		this.classUserService = classUserService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	// =====================================================================================

	@Override
	public Map<String, Object> searchInviteParentList(int page, int pagesize,
			Long cid) {
		String sql = " from invite_parent ip where cid=? order by state,ctime desc";
		String sql_first = sql;
		return commonDao
				.queryPage(
						"select ip.*,(select sname from class_student where csid=ip.csid) as name_student "
								+ sql, "select count(*) " + sql_first, page,
						pagesize, new Object[] { cid }, new Object[] { cid },
						new InviteParentRowMapper(
								InviteParentRowMapper.AND_STUDENTNAME));

	}

	@Override
	public InviteParent searchInviteParentById(Long ipid) {
		return (InviteParent) commonDao
				.listByObject(
						"select ip.*,(select sname from class_student where csid=ip.csid) as name_student,"
								+ "(select tname from school_teacher where tid=ip.tid) as name_teacher,"
								+ "(select cname from classes where cid=ip.cid) as name_class,"
								+ "(select name from school where sid=(select sid from classes where cid=ip.cid)) as name_school,"
								+ "(select uid from class_student where csid=ip.csid) as baby_uid "
								+ " from invite_parent ip where ipid=? ",
						new Object[] { ipid }, new InviteParentRowMapper(
								InviteParentRowMapper.AND_STUDENTNAME_MESSAGE));
	}

	@Override
	public InviteParent searchInviteParentByPhone(String phone, Short state) {
		String sql = "select ip.* from invite_parent ip where phone=? ";
		if (state != null) {
			sql = sql + " and state=" + state;
		}
		sql = sql + " order by ctime desc limit 1";
		return (InviteParent) commonDao.listByObject(sql,
				new Object[] { phone }, new InviteParentRowMapper());

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<InviteParent> searchInviteParentListByState(short inviteTypeWait) {
		String sql = "select ip.* from invite_parent ip where state=? ";
		return (List<InviteParent>) commonDao.list(sql,
				new Object[] { inviteTypeWait }, new InviteParentRowMapper());
	}

	@Override
	public int insertInviteParent(InviteParent inviteParent) {
		commonDao.update(
				"delete from invite_parent where phone=? and state=? ",
				new Object[] { inviteParent.getPhone(),
						InviteRequestUtil.INVITE_TYPE_WAIT });
		KeyHolder kh = commonDao
				.insert(InviteParentRowMapper
						.getPreparedStatementCreator(inviteParent),
						new GeneratedKeyHolder());
		if (kh != null) {
			// 发送短信
			inviteParent = searchInviteParentById(kh.getKey().longValue());
			String phMessage = InviteRequestUtil
					.getIRParentMessage(inviteParent.getName_teacher(),
							inviteParent.getName_student(),
							inviteParent.getName_class(),
							inviteParent.getName_school());
			// sysPhoneMessageService.insertSendPhoneMessage(inviteParent.getPhone(),
			// phMessage);
			sysPhoneMessageService.insertSchoolPhoneMessageMobile(
					inviteParent.getPhone(), phMessage, null, null, 0, null);
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int insertInviteParentList(Long tid, Long cid,
			String invitePar_message) {
		int s = 1;
		Timestamp ctime = new Timestamp(new Date().getTime());
		for (String strtmp : invitePar_message.split("@")) {
			if (!"".equals(strtmp)) {
				String[] strList = strtmp.split(",");
				String csid = strList[0];
				String relation = strList[1];
				String pname = strList[2];
				String phone = strList[Constant.num_3];
				InviteParent inviteParent = new InviteParent(null, pname,
						phone, Long.valueOf(csid), relation, tid, cid, null,
						ctime);
				s = insertInviteParent(inviteParent);
				if (s == 0) {
					return 0;
				}
			}
		}
		return s;
	}

	@Override
	public int insertParentList(Long tid, Long cid, String invitePar_message) {
		int s = 1;
		Timestamp ctime = new Timestamp(new Date().getTime());

		for (String strtmp : invitePar_message.split("@")) {
			if (!"".equals(strtmp)) {
				// 封装数据，插入添加记录表中
				String[] strList = strtmp.split(",");
				String csid = strList[0];
				String relation = strList[1];
				String pname = strList[2];
				String phone = strList[Constant.num_3];
				InviteParent inviteParent = new InviteParent(null, pname,
						phone, Long.valueOf(csid), relation, tid, cid, null,
						ctime);

				KeyHolder kh = commonDao.insert(InviteParentRowMapper
						.getPreparedStatementCreator(inviteParent),
						new GeneratedKeyHolder());
				if (kh != null) {
					// 没有家长账号则新建一个账号,短信内容有所不同
					InviteParent ip = searchInviteParentById(kh.getKey()
							.longValue());
					User user_parent = userService.searchUserByCondition(ip
							.getPhone());
					String pwd = "";
					if (user_parent == null) {
						pwd = RandomUtil.genRandomNum(Constant.num_6);
						user_parent = new User(ip.getPhone(),
								MD5Util.getMD5(pwd), ip.getPname(),
								ip.getPhone());
						userService.insertUserNormal(user_parent);
						user_parent = userService.searchUserByCondition(ip
								.getPhone());
					} else {
						// 如果已存在帐号，更新手机号码和昵称
						userService.updateUserInfoNew(user_parent.getAccount(),
								ip.getPhone(), ip.getPname());
					}

					int num = commonDao
							.countByQuali(
									" from class_parent where uid=? and cid=? and csid=?",
									new Object[] { user_parent.getUid(),
											ip.getCid(), ip.getCsid() });
					if (num == 0) {
						ClassParent classParent = new ClassParent(null,
								user_parent.getUid(), ip.getCid(),
								ip.getPname(), ip.getCsid(), ctime,
								ip.getRelation());
						classUserService.insertClassParent(classParent);
						commonDao
								.update("insert into parent_baby(parent_uid,baby_uid,relation) values(?,?,?) ",
										new Object[] { user_parent.getUid(),
												ip.getBaby_uid(),
												ip.getRelation() });
					}
					// 发送短信
					inviteParent = searchInviteParentById(kh.getKey()
							.longValue());
					String phMessage = InviteRequestUtil.getAddParentMessage(
							inviteParent.getName_teacher(),
							inviteParent.getName_student(),
							inviteParent.getName_class(),
							inviteParent.getName_school(),
							user_parent.getAccount(), pwd);
					// 新增发送记录
					// sysPhoneMessageService.insertSendPhoneMessage(inviteParent.getPhone(),
					// phMessage);
					sysPhoneMessageService.insertSchoolPhoneMessageMobile(
							inviteParent.getPhone(), phMessage, null, null, 0,
							null);
					s = 1;
				} else {
					s = 0;
				}

				if (s == 0) {
					return 0;
				}
			}
		}
		return s;
	}

	@Override
	public int updateParentList(Long tid, Long cid, String updatePar_message) {
		int s = 1;

		for (String strtmp : updatePar_message.split("@")) {
			if (!"".equals(strtmp)) {
				// 解析数据
				String[] strList = strtmp.split(",");
				String cpid = strList[0];
				String relation = strList[1];
				String pname = strList[2];
				String phone = strList[Constant.num_3];

				ClassParent cp = (ClassParent) commonDao.listByObject(
						"select cp.*,u.account from class_parent cp left join user u "
								+ "on cp.uid = u.uid where cp.cpid = ?",
						new Object[] { cpid }, new ClassParentRowMapper(
								ClassParentRowMapper.AND_ACC));
				if (cp.getAccount().equals(phone)) {
					// 电话号码没变，直接修改
					commonDao
							.update("update class_parent set relation=?,pname=? where cpid = ?",
									new Object[] { relation, pname, cpid });
				} else {
					User u = userService.searchUserByCondition(phone);
					// 已有用户
					if (u != null) {
						userService.updateUserInfoNew(phone, phone, pname);
						commonDao
								.update("update class_parent set uid=?,relation=?,pname=? where cpid=?",
										new Object[] { u.getUid(), relation,
												pname, cpid });
					} else {
						// 修改用户的帐号
						commonDao
								.update("update user set account=?,phone=?,nickname=? where uid = ?",
										new Object[] { phone, phone, pname,
												cp.getUid() });
						commonDao
								.update("update class_parent set relation=?,pname=? where cpid=?",
										new Object[] { relation, pname, cpid });
					}

				}
			}
		}
		return s;
	}

	@Override
	public int deleteInviteParent(Long ipid) {
		if (commonDao.update("delete from invite_parent where ipid=?",
				new Object[] { ipid }) > 0) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int updateInviteParent(Long ipid, Short state) {
		int returnInt = 0;
		Timestamp ctime = new Timestamp(new Date().getTime());
		if (commonDao.update("update invite_parent set state=? where ipid=?",
				new Object[] { state, ipid }) > 0) {
			InviteParent ip = searchInviteParentById(ipid);
			if (state == InviteRequestUtil.INVITE_TYPE_AGREE) {// 同意:添加class_parent,parent_baby
				// 没有家长账号则新建一个账号,短信内容有所不同
				User user_parent = userService.searchUserByCondition(ip
						.getPhone());
				String pwd = "";
				if (user_parent == null) {
					pwd = RandomUtil.genRandomNum(Constant.num_6);
					user_parent = new User(ip.getPhone(), MD5Util.getMD5(pwd),
							ip.getPname(), ip.getPhone());
					userService.insertUserNormal(user_parent);
					user_parent = userService.searchUserByCondition(ip
							.getPhone());
				}

				int num = commonDao.countByQuali(
						" from class_parent where uid=? and cid=? and csid=?",
						new Object[] { user_parent.getUid(), ip.getCid(),
								ip.getCsid() });
				if (num == 0) {
					ClassParent classParent = new ClassParent(null,
							user_parent.getUid(), ip.getCid(), ip.getPname(),
							ip.getCsid(), ctime, ip.getRelation());
					classUserService.insertClassParent(classParent);
					commonDao
							.update("insert into parent_baby(parent_uid,baby_uid,relation) values(?,?,?) ",
									new Object[] { user_parent.getUid(),
											ip.getBaby_uid(), ip.getRelation() });
					// 发送回执短信
					String phMessage = InviteRequestUtil.returnIRParentMessage(
							ip.getPhone(), ip.getName_student(),
							ip.getName_class(), ip.getName_school(), pwd);
					// sysPhoneMessageService.insertSendPhoneMessage(ip.getPhone(),
					// phMessage);
					sysPhoneMessageService.insertSchoolPhoneMessageMobile(
							ip.getPhone(), phMessage, null, null, 0, null);
				}
				returnInt = 1;
			}
		}

		return returnInt;
	}

	// =====================================================================================

	@Override
	public Map<String, Object> searchInviteTeacherList(int page, int pagesize,
			Long cid, Integer sid) {
		String sql = " from invite_teacher it where sid=? ";
		if (cid != null) {
			sql = sql + "and cid=" + cid;
		}
		sql = sql + "  order by state,ctime desc";
		String sql_first = sql;
		return commonDao.queryPage(
				"select *,(select name from school_grade where gid=it.gid) as gname "
						+ sql, "select count(*) " + sql_first, page, pagesize,
				new Object[] { sid, }, new Object[] { sid },
				new InviteTeacherRowMapper(InviteTeacherRowMapper.AND_GNAME));
	}

	@Override
	public InviteTeacher searchInviteTeacherById(Long itid) {
		return (InviteTeacher) commonDao
				.listByObject(
						"select it.*,(select name from school where sid=it.sid) as name_school,(select cname from classes where cid=it.cid) as name_class,"
								+ "(select tname from school_teacher where tid=it.tid) as name_teacher "
								+ " from invite_teacher it where it.itid=? ",
						new Object[] { itid }, new InviteTeacherRowMapper(
								InviteTeacherRowMapper.AND_INVITETEACHER));
	}

	@Override
	public InviteTeacher searchInviteTeacherByPhone(String phone, Short state) {
		String sql = "select it.* from invite_teacher it where phone=? ";
		if (state != null) {
			sql = sql + " and state=" + state;
		}
		sql = sql + " order by ctime desc limit 1";
		return (InviteTeacher) commonDao.listByObject(sql,
				new Object[] { phone }, new InviteTeacherRowMapper());

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<InviteTeacher> searchInviteTeacherListByState(
			short inviteTypeWait) {
		String sql = "select it.* from invite_teacher it where state=? ";
		return (List<InviteTeacher>) commonDao.listByObject(sql,
				new Object[] { inviteTypeWait }, new InviteTeacherRowMapper());
	}

	@Override
	public int insertInviteTeacher(InviteTeacher inviteTeacher) {
		commonDao.update(
				"delete from invite_teacher where phone=? and state=? ",
				new Object[] { inviteTeacher.getPhone(),
						InviteRequestUtil.INVITE_TYPE_WAIT });
		KeyHolder kh = commonDao.insert(InviteTeacherRowMapper
				.getPreparedStatementCreator(inviteTeacher),
				new GeneratedKeyHolder());
		if (kh != null) {
			// 发送短信
			inviteTeacher = searchInviteTeacherById(kh.getKey().longValue());
			String phMessage = InviteRequestUtil.getIRTeacherMessage(
					inviteTeacher.getName_teacher(),
					inviteTeacher.getName_school(),
					inviteTeacher.getName_class());
			// sysPhoneMessageService.insertSendPhoneMessage(inviteTeacher.getPhone(),
			// phMessage);
			sysPhoneMessageService.insertSchoolPhoneMessageMobile(
					inviteTeacher.getPhone(), phMessage, null, null, 0, null);
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int insertInviteTeacherList(Integer sid, Long cid, Long tid,
			String inviteTea_message) {
		int s = 1;
		Timestamp ctime = new Timestamp(new Date().getTime());
		for (String strtmp : inviteTea_message.split("@")) { // tname,gid,phone
			if (!"".equals(strtmp)) {
				String[] strList = strtmp.split(",");
				String tname = strList[0];
				Long gid = Long.valueOf(strList[1]);
				if (-1L == gid) {
					gid = null;
				}
				String phone = strList[2];
				InviteTeacher inviteTeacher = new InviteTeacher(null, tname,
						phone, gid, sid, cid, tid, null, ctime);
				s = insertInviteTeacher(inviteTeacher);
				if (s == 0) {
					return 0;
				}
			}
		}
		return s;
	}

	@Override
	public int insertTeacherList(Integer sid, Long cid, Long tid,
			String inviteTea_message) {
		int s = 1;
		Timestamp ctime = new Timestamp(new Date().getTime());
		for (String strtmp : inviteTea_message.split("@")) { // tname,gid,phone
			if (!"".equals(strtmp)) {
				// 封装数据，插入添加记录表中
				String[] strList = strtmp.split(",");
				String tname = strList[0];
				Long gid = Long.valueOf(strList[1]);
				if (-1L == gid) {
					gid = null;
				}
				String phone = strList[2];
				InviteTeacher inviteTeacher = new InviteTeacher(null, tname,
						phone, gid, sid, cid, tid, null, ctime);
				KeyHolder kh = commonDao.insert(InviteTeacherRowMapper
						.getPreparedStatementCreator(inviteTeacher),
						new GeneratedKeyHolder());
				if (kh != null) {

					InviteTeacher it = searchInviteTeacherById(kh.getKey()
							.longValue());
					// 没有教师账号则新建一个账号
					User user_teacher = userService.searchUserByCondition(it
							.getPhone());
					String pwd = "";
					if (user_teacher == null) {
						pwd = RandomUtil.genRandomNum(Constant.num_6);
						user_teacher = new User(it.getPhone(),
								MD5Util.getMD5(pwd), it.getTname(),
								it.getPhone());
						userService.insertUserNormal(user_teacher);
						user_teacher = userService.searchUserByCondition(it
								.getPhone());
					}
					SchoolTeacher schoolTeacher = (SchoolTeacher) commonDao
							.listByObject(
									"select * from school_teacher where uid=? and sid=?",
									new Object[] { user_teacher.getUid(),
											it.getSid() },
									new SchoolTeacherRowMapper());
					if (schoolTeacher == null) {
						if (gid != null && gid != 0) {
							schoolTeacher = new SchoolTeacher(null,
									user_teacher.getUid(), it.getSid(),
									it.getTname(), gid, ctime, null);
						} else {
							schoolTeacher = new SchoolTeacher(null,
									user_teacher.getUid(), it.getSid(),
									it.getTname(), null, ctime, null);
						}
						KeyHolder kh1 = commonDao.insert(SchoolTeacherRowMapper
								.getPreparedStatementCreator(schoolTeacher),
								new GeneratedKeyHolder());
						schoolTeacher.setTid(kh1.getKey().longValue());
					}
					if (it.getCid() != null && it.getCid() != 0) {
						int class_num = commonDao.countByQuali(
								" from class_teacher where tid=? and cid=?",
								new Object[] { schoolTeacher.getTid(),
										it.getCid() });
						if (class_num == 0) {
							ClassTeacher classTeacher = new ClassTeacher(null,
									schoolTeacher.getTid(), it.getCid(), ctime,
									null);
							classUserService.insertClassTeacher(classTeacher);
						}
					}

					// 发送短信
					inviteTeacher = searchInviteTeacherById(kh.getKey()
							.longValue());
					String phMessage = InviteRequestUtil.getAddTeacherMessage(
							inviteTeacher.getName_teacher(),
							inviteTeacher.getName_school(),
							inviteTeacher.getName_class(),
							user_teacher.getAccount(), pwd);
					// sysPhoneMessageService.insertSendPhoneMessage(inviteTeacher.getPhone(),
					// phMessage);
					sysPhoneMessageService.insertSchoolPhoneMessageMobile(
							inviteTeacher.getPhone(), phMessage, null, null, 0,
							null);
					s = 1;
				} else {
					s = 0;
				}

				if (s == 0) {
					return 0;
				}
			}
		}
		return s;
	}

	@Override
	public int deleteInviteTeacher(Long itid) {
		if (commonDao.update("delete from invite_teacher where itid=?",
				new Object[] { itid }) > 0) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int updateInviteTeacher(Long itid, Short state) {
		int returnInt = 0;
		Timestamp ctime = new Timestamp(new Date().getTime());
		if (commonDao.update("update invite_teacher set state=? where itid=?",
				new Object[] { state, itid }) > 0) {
			InviteTeacher it = searchInviteTeacherById(itid);
			if (state == InviteRequestUtil.INVITE_TYPE_AGREE) {// 同意:添加school_teacher,class_teacher(可无)
				// 没有教师账号则新建一个账号,短信内容有所不同
				User user_teacher = userService.searchUserByCondition(it
						.getPhone());
				String pwd = "";
				if (user_teacher == null) {
					pwd = RandomUtil.genRandomNum(Constant.num_6);
					user_teacher = new User(it.getPhone(), MD5Util.getMD5(pwd),
							it.getTname(), it.getPhone());
					userService.insertUserNormal(user_teacher);
					user_teacher = userService.searchUserByCondition(it
							.getPhone());
				}
				SchoolTeacher schoolTeacher = (SchoolTeacher) commonDao
						.listByObject(
								"select * from school_teacher where uid=? and sid=?",
								new Object[] { user_teacher.getUid(),
										it.getSid() },
								new SchoolTeacherRowMapper());
				if (schoolTeacher == null) {
					Long gid = it.getGid();
					if (gid != null && gid != 0) {
						schoolTeacher = new SchoolTeacher(null,
								user_teacher.getUid(), it.getSid(),
								it.getTname(), gid, ctime, null);
					} else {
						schoolTeacher = new SchoolTeacher(null,
								user_teacher.getUid(), it.getSid(),
								it.getTname(), null, ctime, null);
					}
					KeyHolder kh = commonDao.insert(SchoolTeacherRowMapper
							.getPreparedStatementCreator(schoolTeacher),
							new GeneratedKeyHolder());
					schoolTeacher.setTid(kh.getKey().longValue());
				}
				if (it.getCid() != null && it.getCid() != 0) {
					int class_num = commonDao
							.countByQuali(
									" from class_teacher where tid=? and cid=?",
									new Object[] { schoolTeacher.getTid(),
											it.getCid() });
					if (class_num == 0) {
						ClassTeacher classTeacher = new ClassTeacher(null,
								schoolTeacher.getTid(), it.getCid(), ctime,
								null);
						classUserService.insertClassTeacher(classTeacher);
					}
				}
				// 发送回执短信
				String phMessage = InviteRequestUtil.returnIRTeacherMessage(
						it.getPhone(), it.getName_school(), it.getName_class(),
						pwd);
				// sysPhoneMessageService.insertSendPhoneMessage(it.getPhone(),
				// phMessage);
				sysPhoneMessageService.insertSchoolPhoneMessageMobile(
						it.getPhone(), phMessage, null, null, 0, null);
				returnInt = 1;
			}
		}

		return returnInt;
	}

	// =====================================================================================

	@Override
	public Map<String, Object> searchRequestParentList(int page, int pagesize,
			Long cid, Short state) {
		String sql = "  from request_parent rp where cid=? ";
		if (state != null) {
			sql += " and state=" + state + " order by state,ctime desc";
		}
		String sql_first = sql;
		return commonDao.queryPage(
				"select rp.*,(select nickname from user where uid=rp.baby_uid) as name_student"
						+ sql, "select count(*) " + sql_first, page, pagesize,
				new Object[] { cid }, new Object[] { cid },
				new RequestParentRowMapper(
						RequestParentRowMapper.AND_PARENTNAMES));
	}

	@Override
	public RequestParent searchRequestParentById(Long rpid) {
		return (RequestParent) commonDao
				.listByObject(
						"select rp.*,(select nickname from user where uid=rp.parent_uid) as name_parent,"
								+ "(select nickname from user where uid=rp.baby_uid) as name_student"
								+ " from request_parent rp where rpid=? ",
						new Object[] { rpid }, new RequestParentRowMapper(
								RequestParentRowMapper.AND_PARENTNAMES));
	}

	@Override
	public int insertRequestParent(RequestParent requestParent) {
		KeyHolder kh = commonDao.insert(RequestParentRowMapper
				.getPreparedStatementCreator(requestParent),
				new GeneratedKeyHolder());
		if (kh != null) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int deleteRequestParent(Long rpid) {
		if (commonDao.update("delete from request_parent where rpid=?",
				new Object[] { rpid }) > 0) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int updateRequestParent(Long rpid, Short state, Long cid) {
		int returnInt = 0;
		Timestamp ctime = new Timestamp(new Date().getTime());
		if (commonDao.update(
				"update request_parent set state=? where cid=? and rpid=?",
				new Object[] { state, cid, rpid }) > 0) {
			RequestParent rp = searchRequestParentById(rpid);
			if (state == InviteRequestUtil.REQUEST_TYPE_AGREE) {// 同意:添加class_student,class_parent
				ClassStudent classStudent = (ClassStudent) commonDao
						.listByObject(
								"select *  from class_student where uid=? and cid=? ",
								new Object[] { rp.getBaby_uid(), rp.getCid() },
								new ClassStudentRowMapper());
				if (classStudent == null) {
					classStudent = new ClassStudent(null, rp.getBaby_uid(),
							rp.getName_student(), rp.getCid(), ctime);
					KeyHolder kh = commonDao.insert(ClassStudentRowMapper
							.getPreparedStatementCreator(classStudent),
							new GeneratedKeyHolder());
					classStudent.setCsid(kh.getKey().longValue());
				}

				int num_parent = commonDao
						.countByQuali(
								" from class_parent where uid=? and cid=? "
										+ "and csid=(select csid from class_student where uid=? and cid=? )",
								new Object[] { rp.getParent_uid(), rp.getCid(),
										rp.getBaby_uid(), rp.getCid() });
				if (num_parent == 0) {
					ClassParent classParent = new ClassParent(null,
							rp.getParent_uid(), rp.getCid(),
							rp.getName_parent(), classStudent.getCsid(), ctime,
							rp.getRelation());
					classUserService.insertClassParent(classParent);
				}
				// 加一条通知
				// String phMessage =
				// InviteRequestUtil.returnIRTeacherMessage(flag, it.getPhone(),
				// it.getName_school(), it.getName_class());
				commonDao.update(
						"insert into notice(ruid,content,cdate) values(?,?,?)",
						new Object[] { rp.getParent_uid(), "您的加入学校申请已通过审核.",
								ctime });
			} else {
				commonDao.update(
						"insert into notice(ruid,content,cdate) values(?,?,?)",
						new Object[] { rp.getParent_uid(),
								"您的加入学校申请已被学校管理员拒绝.", ctime });
			}
			returnInt = 1;
		}

		return returnInt;
	}

	// =====================================================================================

	@Override
	public Map<String, Object> searchRequestTeacherList(int page, int pagesize,
			Long cid, Integer sid, Short state) {
		String sql = " from request_teacher rt where 1=1 ";
		if (sid != null) {
			sql = sql + " and sid=" + sid;
		}
		if (cid != null) {
			sql = sql + " and cid=" + cid;
		}
		if (state != null) {
			sql = sql + " and state=" + state;
		}
		sql = sql + " order by state,ctime desc";
		String sql_first = sql;
		return commonDao.queryPage("select rt.* " + sql, "select count(*) "
				+ sql_first, page, pagesize, new Object[] {}, new Object[] {},
				new RequestTeacherRowMapper());
	}

	@Override
	public RequestTeacher searchRequestTeacherById(Long rtid) {
		return (RequestTeacher) commonDao.listByObject(
				"select * from request_teacher where rtid=? ",
				new Object[] { rtid }, new RequestTeacherRowMapper());
	}

	@Override
	public int insertRequestTeacher(RequestTeacher requestTeacher) {
		KeyHolder kh = commonDao.insert(RequestTeacherRowMapper
				.getPreparedStatementCreator(requestTeacher),
				new GeneratedKeyHolder());
		if (kh != null) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int deleteRequestTeacher(Long rtid) {
		if (commonDao.update("delete from request_teacher where rtid=?",
				new Object[] { rtid }) > 0) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int updateRequestTeacher(Long rtid, Short state, Long tid) {
		int returnInt = 0;
		Timestamp ctime = new Timestamp(new Date().getTime());
		if (commonDao.update(
				"update request_teacher set state=?,tid=? where rtid=?",
				new Object[] { state, tid, rtid }) > 0) {
			RequestTeacher rt = searchRequestTeacherById(rtid);
			if (state == InviteRequestUtil.REQUEST_TYPE_AGREE) {// 同意:添加school_teacher,class_teacher(可无)

				SchoolTeacher schoolTeacher = (SchoolTeacher) commonDao
						.listByObject(
								"select * from school_teacher where uid=? and sid=?",
								new Object[] { rt.getUid(), rt.getSid() },
								new SchoolTeacherRowMapper());
				if (schoolTeacher == null) {
					Long gid = rt.getGid();
					if (gid != null && gid != 0) {
						schoolTeacher = new SchoolTeacher(null, rt.getUid(),
								rt.getSid(), rt.getTname(), rt.getGid(), ctime,
								null);
					} else {
						schoolTeacher = new SchoolTeacher(null, rt.getUid(),
								rt.getSid(), rt.getTname(), null, ctime, null);
					}

					KeyHolder kh = commonDao.insert(SchoolTeacherRowMapper
							.getPreparedStatementCreator(schoolTeacher),
							new GeneratedKeyHolder());
					schoolTeacher.setTid(kh.getKey().longValue());
				}
				if (rt.getCid() != null && rt.getCid() != 0) {
					int class_num = commonDao
							.countByQuali(
									" from class_teacher where tid=? and cid=?",
									new Object[] { schoolTeacher.getTid(),
											rt.getCid() });
					if (class_num == 0) {
						ClassTeacher classTeacher = new ClassTeacher(null,
								schoolTeacher.getTid(), rt.getCid(), ctime,
								null);
						classUserService.insertClassTeacher(classTeacher);
					}
				}
				// 加一条系统通知
				commonDao.update(
						"insert into notice(ruid,content,cdate) values(?,?,?)",
						new Object[] { rt.getUid(), "您的加入学校申请已通过审核.", ctime });
			} else {// 拒绝
				commonDao
						.update("insert into notice(ruid,content,cdate) values(?,?,?)",
								new Object[] { rt.getUid(),
										"您的加入学校申请已被学校管理员拒绝.", ctime });
			}
			returnInt = 1;
		}

		return returnInt;
	}

	// =====================================================================================

	@Override
	public void updateInviteRefuse(String phone) {
		InviteParent ip = searchInviteParentByPhone(phone,
				InviteRequestUtil.INVITE_TYPE_WAIT);
		InviteTeacher it = searchInviteTeacherByPhone(phone,
				InviteRequestUtil.INVITE_TYPE_WAIT);
		if (ip != null) {
			commonDao.update(
					"update invite_parent set state=? where ipid=?",
					new Object[] { InviteRequestUtil.INVITE_TYPE_REFUSE,
							ip.getIpid() });
		}
		if (it != null) {
			commonDao.update(
					"update invite_teacher set state=? where itid=?",
					new Object[] { InviteRequestUtil.INVITE_TYPE_REFUSE,
							it.getItid() });
		}
	}

	public void setSysPhoneMessageService(
			ISysPhoneMessageService sysPhoneMessageService) {
		this.sysPhoneMessageService = sysPhoneMessageService;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Object> requestTeacherListByState(Integer sid, Integer uid) {
		String sql = "select * from parent_baby where parent_uid=?";
		List<Object> list = (List<Object>) commonDao.list(sql,
				new Object[] { uid });
		if (list.size() > 0) {
			sql = "select rp.* from request_parent rp left join "
					+ "  classes c on c.cid=rp.cid where rp.state=0 and c.sid=? and parent_uid=?";
			return (List<Object>) commonDao.list(sql,
					new Object[] { sid, uid }, new RequestParentRowMapper());
		}
		sql = "select rt.* from request_teacher rt where  rt.state=1  and rt.sid=? and uid=? ";
		return (List<Object>) commonDao.list(sql, new Object[] { sid, uid },
				new RequestTeacherRowMapper());
	}
}
